/*
 * @File: 
 * @Author: Cc
 * @Date: 2022-02-24 16:29:35
 * @LastEditors: Cc
 * @LastEditTime: 2022-04-02 14:40:36
 * @FilePath: \test-unicorn\src\pages\testcode\index.tsx
 */
import React, { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import styles from "./index.less"
const Testcode = (props: any,ref: any) => {
  var p = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("我执行成功了。");
    }, 2000);
    reject("我失败了");
  });
  console.log(p);
  p.then(res => {
    console.log("then", res)
  }).catch(err => {
    // throw 
    return new Error(err);
  })


  
  const { parent, change } = props;
  console.log("props传过来的值", parent, change);
  console.log("props", props);
  const [str, setStr] = useState("www");
  const [num, setNum] = useState(0);
  const [arr, setArr] = useState([{id: "1", name: "小明", age: 15}, {id: "2", name: "小王", age: 10}]);
  const [val, setVal] = useState(0);
  const [show] = useState(false);
  useImperativeHandle(ref,() => ({
    onchange
  }))
  const onchange = () => {
    change(num);
    console.log("ref啊")
  }
  useEffect(() => {
    // console.log("我只执行一次")
  },[])
  useEffect(() => {
    console.log("我只在num变化时触发")
  },[num])
  const addval = () => {
    setVal(val + 1)
    props.getVal(val + 1)
  };

  let testArr = [
    {name: "xiaoming", age: 18, gender: "男"},
    {name: "xiaoming", age: 18, gender: "男"},
    {name: "xiaohong", age: 19, gender: "女"},
    {name: "who", age: 20, gender: "人妖"}
  ];
  let obj = {};
  testArr.map(item => {
    if (item.name) {
      if(!obj[item.name]) {
        console.log("obj[item.name]1111",obj[item.name]);
        obj[item.name] = [];
      }
      console.log("obj[item.name]",obj[item.name]);
      obj[item.name].push(item);
    } else {
      if (obj["测试"]) {
        obj["测试"] = [];
      }
      obj["测试"].push(item)
    }
  })
  // console.log(obj);
  return (
    <>
      <div className={styles.testhook}>
        <button onClick={onchange}>点我给父组件传值</button>
        <div onClick={() => {setStr("hello world")}}>{show ? str : ""}</div>
        <div onClick={() => {setNum(num + 1)}}>{num}</div>
        <ul>
          {arr.length > 0 && arr.map(item => {
            return (
              <li key={item.id}>
                my name is{item.name},this year{item.age}.
              </li>
            )
          })}
        </ul>
        <div onClick={() => {setArr([...arr, {id: String(Math.random()), name: "xiaolu", age: Math.floor(Math.random() * 10)}])}}>更改数组</div>
      </div>
      <div>
        <div className={styles.form_confirm}>
          <div className={styles.form_clear}>
            <span onClick={addval}>选择</span>
            <span>清除{val}</span>
          </div>
        </div>
      </div>
    </>
  )
}
export default forwardRef(Testcode);

